package com.netease.financial.base.update;

import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.netease.financial.R;
import com.netease.financial.common.security.SecurityJNI;
import com.netease.financial.common.util.DownloadManagerPro;
import com.netease.financial.common.util.NfsLog;
import com.netease.financial.common.util.PackageUtils;
import com.netease.financial.common.util.preferences.DownloadPreferencesHelper;

import java.io.File;

public class ApkDownloadService extends Service {

    private static final String TAG = ApkDownloadService.class.getSimpleName();

    private static final String DOWNLOAD_FOLDER_NAME = "download";
    private static final String DOWNLOAD_FILE_NAME = "FortuneClub.apk";

    public static final String ARG_APK_URL = "apkUrl";

    private DownloadManager mDownloadManager;
    private DownloadManagerPro mDownloadManagerPro;

    private long mDownloadId = 0;

    private CompleteReceiver mCompleteReceiver;

    private String mApkUrl;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        mDownloadManagerPro = new DownloadManagerPro(mDownloadManager);

        mCompleteReceiver = new CompleteReceiver();
        /** register download success broadcast **/
        registerReceiver(mCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mApkUrl = intent.getStringExtra(ARG_APK_URL);

        NfsLog.d(TAG, "ApkDownloadService.mApkUrl ==== " + mApkUrl);
        if (TextUtils.isEmpty(mApkUrl)) {
            return super.onStartCommand(intent, flags, startId);
        }
//        initData();

        mDownloadId = DownloadPreferencesHelper.getDownloadIdForUrl(mApkUrl);

        int status = mDownloadManagerPro.getDownloadStatus(mDownloadId);

        if (isDownloading(status)) {
            NfsLog.d(TAG, "isDownloading");
        } else {
            if (status == DownloadManager.STATUS_FAILED) {
                download();
            } else if (status == DownloadManager.STATUS_SUCCESSFUL) {
                NfsLog.d(TAG, "STATUS_SUCCESSFUL");
                download();
            } else {
                download();
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mCompleteReceiver);

    }

    private void download() {
        File file = new File(getDownloadPath(), DOWNLOAD_FILE_NAME);
        if (file.exists()) {
            file.delete();
        }

        try {
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mApkUrl));
            request.setDestinationInExternalFilesDir(this, DOWNLOAD_FOLDER_NAME, DOWNLOAD_FILE_NAME);

            request.setTitle(getString(R.string.app_name));
            request.setDescription(getString(R.string.downloading));
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
            request.setVisibleInDownloadsUi(false);
            request.addRequestHeader("AppId", SecurityJNI.getAppId());
            // request.allowScanningByMediaScanner();
            // request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
            // request.setShowRunningNotification(false);
            // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
            request.setMimeType("application/vnd.android.package-archive");
            mDownloadId = mDownloadManager.enqueue(request);
            /** save download id to preferences **/
            DownloadPreferencesHelper.saveDownloadIdForUrl(mApkUrl, mDownloadId);
        } catch (Exception e) {
            e.printStackTrace();
            ApkDownloadService.this.stopSelf();
        }

    }

    @NonNull
    private File getDownloadPath() {
        File downloadPath = new File(getFilesDir(), DOWNLOAD_FOLDER_NAME);
        if (!downloadPath.exists()) {
            downloadPath.mkdir();
        }
        return downloadPath;
    }

    class CompleteReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            /**
             * get the id of download which have download success, if the id is my id and it's status is successful,
             * then install it
             **/
            long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (completeDownloadId == mDownloadId) {
                // if download successful, install apk
                if (mDownloadManagerPro.getStatusById(mDownloadId) == DownloadManager.STATUS_SUCCESSFUL) {
                    installApk(context);
                }
                ApkDownloadService.this.stopSelf();
            }
        }
    }

    private void installApk(Context context) {
        String filePath = mDownloadManagerPro.getFileName(mDownloadId);
        File file = new File(filePath);
        PackageUtils.installApk(context, file);
    }

    public static boolean isDownloading(int downloadManagerStatus) {
        return downloadManagerStatus == DownloadManager.STATUS_RUNNING
                || downloadManagerStatus == DownloadManager.STATUS_PAUSED
                || downloadManagerStatus == DownloadManager.STATUS_PENDING;
    }

}
